<!--
Copyright (c) 2022 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->


<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Inspiration Desk Message</title>
   <style>
        html,body,#container{
            height:100%;
            width:100%;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background-color: #FFFFFF;
        }
        .amap-icon img{
            width: 25px;
            height: 34px;
        }
        .info{
            position: relative;
            margin:0;
            top: 0;
            right: 0;
            min-width: 0;
        }
        .animator {
            width: 500px;
            height: 500px;
        }
        image{
            max-width: 100%;
            height: auto;
            border: 5px solid saddlebrown;
            border-radius: 20px;
            object-fit: contain;
            match-text-direction:true;

        }
    </style>

    </style>
</head>
<body>
<!--<input type="text" id="msg" />-->
<!--<div>连接状态：<span id="status"></span></div>-->
<!--<button type="button" onclick="startDraw()">Click Me!</button>-->

<!--<image  src="./img/gif_6.png"> </image>-->

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script >

    var publish_topic="WEB2M5Stack";
    var subscribe_topic = "M5Stack";
    var sendRobotMessage = "";


// 供 ets 调用函数
// 发送桌面消息
function SendMsg2DeskRobot()
{
    this.send("n你好123n鸿蒙345n桌面456n小助手789n方便又快捷000n","WEB2M5Stack");
}
    const options={
        connectTimeout:4000,
        keepalice:20,
        clean:true,
        clientId:'mqttjsks',
        username:'hellokun',
        password:'123456',
    }
    const client=mqtt.connect('ws://120.55.170.12:8083/mqtt',options)

    client.on('reconnect', (error) => {
     document.getElementById("status").innerText = '正在重连';
     console.log('正在重连:', error)
     })

    client.on('error',(error)=>{
        document.getElementById("status").innerText='Faild';
        console.log('connect faild:',error)
    })

    client.on('connect', (e) => {
        // document.getElementById("status").innerText = '成功';
        console.log('成功连接服务器');
        // 监听接收消息事件
        this.subscribe();
        client.on('message', (topic, message) => {
            console.log("niubility!!!!!");
            console.log('收到来自', topic, '的消息', message.toString())
            if(topic=="M5Stack"){
                 // eg.: 10  // Task1 Todo
                 // 10、20、30、40、50  // Task1-5 All Todo
                 // 11、21、31、41、51  // Task1-5 All Done
                 var isArduino = 0;
                 if(!isArduino)
                 {
                     var jsonObj = JSON.parse(message)
                     var jsonObjTaskNumber = jsonObj.checkbox
                     var jsonObjTaskChecked = jsonObj.checked
                     console.log('jsonObjTaskNumber:'+jsonObjTaskNumber)
                     console.log('jsonObjTaskChecked:'+jsonObjTaskChecked)
                     this.PostMsgToEts(jsonObjTaskNumber.toString()+jsonObjTaskChecked.toString());
                 }
                 else{
                     var TaskNumber = message.toString().substring(0,1);
                     var TaskStatus= message.toString().substring(1,2);
                     console.log('TaskNumber:'+TaskNumber)
                     console.log('TaskStatus:'+TaskStatus)
                     this.PostMsgToEts(TaskNumber+TaskStatus);
                 }
            }
         })
     })

     //订阅话题
     function subscribe() {
         if (client.connected) {
             client.subscribe(this.subscribe_topic);
         }
     }
     //取消订阅话题
     function unsubscribe() {
         if (client.connected) {
             client.unsubscribe(this.subscribe_topic, (error) => {
                 console.log(error || '取消订阅')
             })
        }
    }

    //发布话题数据
     function send(data,what_topic) {
         console.log('send(data) from topic:'+what_topic);
         if (data.length > 0) {
             client.publish(what_topic, data, (error) => {
                console.log(error || '消息发布成功')
             })
            // document.getElementById("msg").value = "";
             console.log("消息发送成功" + data);
         } else {
            alert("发送的消息不能为空");
         }
     }

var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
    if (event.data === '__init_port__') {
        if (event.ports[0] !== null) {
            h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口
            h5Port.onmessage = function (event) {
              // 2. 接收ets侧发送过来的消息.
              var msg = 'Got message from ets:';
              var result = event.data;
              if (typeof(result) === 'string') {
                console.info(`received string message from html5, string is: ${result}`);
                msg = result;
              } else if (typeof(result) === 'object') {
                if (result instanceof ArrayBuffer) {
                  console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
                  msg = msg + 'lenght is ' + result.byteLength;
                } else {
                  console.info('not support');
                }
              } else {
                console.info('not support');
              }
              this.sendRobotMessage = msg.toString();
              console.info('sendRobotMessage = '+this.sendRobotMessage);
              // document.getElementById("getMsg").innerText =  msg;
              send(msg.toString(),"WEB2M5Stack"); //将收到的数据通过mqtt发送到设备。ets可直接调用H5函数，该接口备用
              // 发送桌面消息
              // SendMsg2DeskRobot();
              // this.send("n你好123n鸿蒙345n桌面456n小助手789n方便又快捷000n","WEB2M5Stack");

            }
        }
    }
})

// 3. 使用h5Port往ets侧发送消息.
function PostMsgToEts(data) {
    console.info('H5 to Ets data:'+data);
    if (h5Port) {
      h5Port.postMessage(data);
    } else {
      console.error('h5Port is null, Please initialize first');
    }
}

</script>

</body>
</html>